package com.systemsjr.mpf.expense;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.systemsjr.mpf.IntentHandler;
import com.systemsjr.mpf.MpfActivity;
import com.systemsjr.mpf.R;
import com.systemsjr.mpf.account.Account;
import com.systemsjr.mpf.account.AccountInstance;
import com.systemsjr.mpf.account.ManageAccountActivity;

public class ExpenseList extends ListActivity {

	private SimpleCursorAdapter adapter;
	private ListView listView;
	private Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_expense_list);

		String[] from = { Expense.DESCRIPTION, Expense.AMOUNT,
				Expense.EXPENSE_DATE };

		c = getContentResolver().query(Expense.CONTENT_URI,
				Expense.PROJECTIONS, null, null, null);
		// String[] selectionArgs = { "%", "%", "%" };

		Expense exp = new Expense();

		Bundle bundle = getIntent().getExtras();

		if (bundle != null && bundle.size() > 0) {

			if (bundle.get(Expense.TABLE_NAME) != null) {
				exp = (Expense) bundle.get(Expense.TABLE_NAME);
			}

			/*
			 * selectionArgs = new String[] { (exp.getDescription() != null &&
			 * exp.getDescription() .length() > 0) ? "%" : "%" +
			 * exp.getDescription(), exp.getAccountInstance() == null ? "0" : ""
			 * + exp.getAccountInstance().getId(), exp.getExpenseType() == null
			 * ? "0" : "" + exp.getExpenseType().getId() };
			 */
		}

		String selection = "DESCRIPTION LIKE "
				+ ((exp.getDescription() == null || exp.getDescription()
						.length() > 0) ? "'%'" : "'%" + exp.getDescription()
						+ "%'");

		selection = selection
				+ " AND "
				+ Expense.EXPENSE_TYPE
				+ (exp.getExpenseType() == null ? " > 0" : " = "
						+ exp.getExpenseType().getId());

		selection = selection
				+ " AND "
				+ Expense.ACCOUNT_INSTANCE
				+ (exp.getAccountInstance() == null ? " > 0 " : " =  "
						+ exp.getAccountInstance().getId());

		System.out.println(selection);

		c = getContentResolver().query(Expense.CONTENT_URI,
				Expense.PROJECTIONS, selection, null, null);
		startManagingCursor(c);

		int[] to = { R.id.exp_description, R.id.exp_amount,
				R.id.exp_expense_date };

		adapter = new SimpleCursorAdapter(this, R.layout.expense_list_entry, c,
				from, to, 0);
		listView = getListView();

		listView.setAdapter(adapter);
		
		Button expenseButton = (Button) findViewById(R.id.addExpenseButton);
		expenseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ExpenseList.this,
						ManageExpenseActivity.class);
				startActivity(intent);

			}
		});

		Button expenseTypeButton = (Button) findViewById(R.id.addExpenseTypeButton);
		expenseTypeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(ExpenseList.this,
						ManageExpenseTypeActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(ExpenseList.this,
				ManageExpenseActivity.class);

		if (adapter != null) {
			Cursor c = (Cursor) adapter.getItem(position);

			Expense expense = new Expense();
			SimpleDateFormat sdf = new SimpleDateFormat(Expense.DATE_FORMAT);

			expense.setDescription(c.getString(c
					.getColumnIndex(Expense.DESCRIPTION)));
			expense.setId(c.getLong(c.getColumnIndex(Expense.ID)));
			expense.setAmount(c.getDouble(c.getColumnIndex(Expense.AMOUNT)));
			long instanceFk = c.getLong(c
					.getColumnIndex(Expense.ACCOUNT_INSTANCE));

			/**
			 * Loading the account instance from the database
			 */
			Cursor c1 = getContentResolver().query(AccountInstance.CONTENT_URI,
					AccountInstance.PROJECTIONS, "_id = " + instanceFk, null,
					null);
			
			AccountInstance instance = new AccountInstance();
			
			if(c1.moveToFirst()){
				instance.setId(c1.getLong(c1.getColumnIndex(AccountInstance.ID)));
				instance.setInstance(c1.getString(c1.getColumnIndex(AccountInstance.INSTANCE)));
				instance.setBudget(c1.getDouble(c1.getColumnIndex(AccountInstance.BUDGET)));
				SimpleDateFormat sdf1 = new SimpleDateFormat(AccountInstance.DATE_FORMAT);
				try {
					instance.setStartDate(sdf1.parse(c1.getString(c1.getColumnIndex(AccountInstance.START_DATE))));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				if(c1.getString(c1.getColumnIndex(AccountInstance.CLOSE_DATE)) != null){
					try {
						instance.setCloseDate(sdf1.parse(c1.getString(c1.getColumnIndex(AccountInstance.CLOSE_DATE))));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				//instance.setSpent(c1.getDouble(c1.getColumnIndex(AccountInstance.SPENT)));
			}
			c1.close();
			expense.setAccountInstance(instance);

			/**
			 * Loading the expense type from the database
			 */
			long typeFk = c.getLong(c.getColumnIndex(Expense.EXPENSE_TYPE));
			ExpenseType type = new ExpenseType();
			c1 = getContentResolver().query(ExpenseType.CONTENT_URI, ExpenseType.PROJECTIONS, "_id = " + typeFk, null, null);
			
			if(c1.moveToFirst()){
				type.setId(typeFk);
				type.setCode(c1.getString(c1.getColumnIndex(ExpenseType.CODE)));
				type.setExpenseType(c1.getString(c1.getColumnIndex(ExpenseType.EXPENSE_TYPE)));
			}
			c1.close();
			expense.setExpenseType(type);

			try {
				expense.setExpenseDate(sdf.parse(c.getString(c
						.getColumnIndex(Expense.EXPENSE_DATE))));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			intent.putExtra(Expense.TABLE_NAME, expense);
		}
		startActivityForResult(intent, 1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.expense_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intent = IntentHandler.handleOnOptionsItemSelected(this,
				item.getItemId());
		startActivityForResult(intent, 1);
		return super.onOptionsItemSelected(item);
	}
}
